import axios from 'axios'
import Vue from "vue";
const hcvue = new Vue();

function uploadImage(url,file,bucketName,isload) {
	// 为了让外面可以.then
	let uploaditem = {}
	uploaditem.then = function(thencallback){
		uploaditem.thencallback = thencallback 
		return uploaditem;
	}
		let loading = null
		if(isload) {
			loading = hcvue.$loading({
				lock: true,
				text: '数据加载中',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.0)'
			});
		}
	   let formData = new FormData();
	   formData.append('file', file);
	   formData.append('bucketName', bucketName);
	   formData.append('sourceId', null);
		axios({
			url:url,
			method: 'POST',
			data:formData,
			timeout:0, //无超时
			headers: {
				'Content-Type': 'multipart/form-data',
				 token:sessionStorage.getItem("SYS_Token")
				}
		}).then(res =>{
			if(loading) {
				loading.close();
			}
			if(res.data.code == 200)
			{
				if(uploaditem.thencallback)
				{
					uploaditem.thencallback(res.data.file)
				}
			}
		}).catch((err) => {
			if(loading) {
				loading.close();
			}
		});
	
	return uploaditem;
}

function uploadFile(url,file,bucketName,isload) {
	// 为了让外面可以.then
	let uploaditem = {}
	uploaditem.then = function(thencallback){
		uploaditem.thencallback = thencallback 
		return uploaditem;
	}
	
		let loading = null
		if(isload) {
			loading = hcvue.$loading({
				lock: true,
				text: '数据加载中',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.0)'
			});
		}
	   let formData = new FormData();
	   formData.append('file', file);
	   formData.append('bucketName', bucketName);
	   formData.append('sourceId', null);
		axios({
			url:url,
			method: 'POST',
			data:formData,
			timeout:0, //无超时
			headers: {
				'Content-Type': 'multipart/form-data',
				 token:sessionStorage.getItem("SYS_Token")
				}
		}).then(res =>{
			if(loading) {
				loading.close();
			}
			if(res.data.code == 200)
			{
				if(uploaditem.thencallback)
				{
					uploaditem.thencallback(res.data.file)
				}
			}
		}).catch((err) => {
			if(loading) {
				loading.close();
			}
		});
	
	return uploaditem;
}


 //附件下载
 function downLoad(item) {
	let params = {
		  fileId: item.fileId,
		  fileName: item.fileName
	}
	  axios({method: 'post', url: '/amis-security/file/fileDownloadCommon', data: params, responseType: 'blob'}).then(res => {
			if (!res.data) {
			  return;
			}
			if ("download" in document.createElement("a")) {
			  let url = window.URL.createObjectURL(new Blob([res.data]));
			  let link = document.createElement("a");
			  link.style.display = "none";
			  link.href = url;
			  link.setAttribute("download", params.fileName);
			  document.body.appendChild(link);
			  link.click();
			} else {
			  navigator.msSaveBlob(new Blob([res.data]), params.fileName);
			}
	  })
  }



export {uploadImage,uploadFile};

